from flask import Blueprint, render_template, request
from module_admin.entity.do.base import db
from module_admin.entity.do.content import CourseContent
from module_admin.utils.http import fail_api, success_api, table_api
from module_admin.utils.validate import str_escape

content = Blueprint('content', __name__)


@content.post('/add_course_content')
def add_course_content():
    req_json = request.get_json(force=True)
    content_type = str_escape(req_json.get('content_type'))
    content_url = str_escape(req_json.get('content_url'))
    uploaded_by = str_escape(req_json.get('uploaded_by'))

    if not content_type or not content_url:
        return fail_api(msg="内容类型和内容URL不得为空")

    course_content = CourseContent(content_type=content_type, content_url=content_url, uploaded_by=uploaded_by)
    db.session.add(course_content)
    db.session.commit()
    return success_api(msg="课程内容添加成功")


@content.get('/course_content_list')
def get_all_course_contents():
    # 查询所有课程内容
    contents = CourseContent.query.all()

    # 构建返回数据
    content_list = [
        {
            "id": content.id,
            "content_type": content.content_type,
            "content_url": content.content_url,
            "uploaded_by": content.uploaded_by,
        }
        for content in contents
    ]

    return table_api(data=content_list, msg="获取成功")


@content.post('/edit_course_content/<int:content_id>')
def edit_course_content(content_id):
    req_json = request.get_json(force=True)
    new_content_type = str_escape(req_json.get('content_type'))
    new_content_url = str_escape(req_json.get('content_url'))
    new_uploaded_by = str_escape(req_json.get('uploaded_by'))

    # 查找指定课程内容
    content = CourseContent.query.filter_by(id=content_id).first()

    if not content:
        return fail_api(msg="课程内容不存在")

    # 更新课程内容信息
    if new_content_type:
        content.content_type = new_content_type
    if new_content_url:
        content.content_url = new_content_url
    if new_uploaded_by:
        content.uploaded_by = new_uploaded_by

    db.session.commit()
    return success_api(msg="课程内容编辑成功")


@content.get('/delete_course_content/<int:content_id>')
def delete_course_content(content_id):
    # 查找指定课程内容
    content = CourseContent.query.filter_by(id=content_id).first()

    if not content:
        return fail_api(msg="课程内容不存在")

    # 删除课程内容
    db.session.delete(content)
    db.session.commit()

    return success_api(msg="课程内容删除成功")
